﻿using Max.PH5_2010A.Shopping.IRespository;
using Max.PH5_2010A.Shopping.IService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Max.PH5_2010A.Shopping.Service
{
    public class BaseService<T> : IBaseService<T>
    {
        IBaseRespository<T> _respository;
        IUnitOfWork _unitOfWork;

        public BaseService(IBaseRespository<T> respository, IUnitOfWork unitOfWork)
        {
            _respository = respository;
            _unitOfWork = unitOfWork;
        }

        public int Delete(List<T> ts)
        {
            _respository.Delete(ts);

            var result = _unitOfWork.SaveChanges();
            return result;
        }

        public int Insert(T model)
        {
            _respository.Insert(model);
            var result = _unitOfWork.SaveChanges();
            return result;
        }

        public int Insert(List<T> model)
        {
            _respository.Insert(model);
            var result = _unitOfWork.SaveChanges();
            return result;
        }

        public IQueryable<T> Select()
        {
            return _respository.Select();
        }

        public IQueryable<T> Select(int pageIndex, int pageSize, out int total)
        {
            var list = _respository.Select();
            total = list.Count();
            list = list.Skip((pageIndex - 1) * pageSize).Take(pageSize);
            return list;
        }

        public IQueryable<T> Select<TKey>(Func<T, TKey> sort, bool isAsc)
        {

            if (isAsc)
              return  _respository.Select().OrderBy(sort).AsQueryable();
            else
              return  _respository.Select().OrderByDescending(sort).AsQueryable();

        }

        public int Update(T model)
        {
            _respository.Update(model);

            var result = _unitOfWork.SaveChanges();
            return result;
        }

        //public int Update(T model)
        //{
        //    //开启事务
        //    using (var tran = _unitOfWork.GetDbContext().Database.BeginTransaction())
        //        try
        //        {
        //            _respository.Update(model);
        //            _respository.Insert(model);
        //            _respository.Delete(new List<T> { model });

        //            var result = _unitOfWork.SaveChanges();
        //            //提交事务
        //            tran.Commit();

        //            return result;
        //        }
        //        catch (Exception)
        //        {
        //            //回滚事务
        //            tran.Rollback();

        //            return -1;
        //        }
        //}
    }
}
